﻿Imports System.Data.SqlClient
Imports System.IO
Imports System.Xml

Public Class MSSQLSrv

    Private Const SQL_TABLES As String =
        "SELECT " &
            "name " &
        "FROM sys.Tables " &
        "WHERE type_desc = 'USER_TABLE' " &
        "ORDER BY name"

    Public Shared Function RaedSchema(ConnStr As String, OutDir As String) As Boolean
        '1.Create XML data
        '1.1. Read database objects
        Dim Conn As New SqlConnection(ConnStr)
        Dim DBName As String = Conn.Database
        Dim TablesTable As New DataTable
        Dim TablesTableAdapter As New SqlDataAdapter(SQL_TABLES, Conn)
        TablesTableAdapter.Fill(TablesTable)
        Conn.Close()
        Conn.Dispose()
        '1.2. Build XML with them
        Dim XDoc As New XmlDocument
        Dim Decl As XmlDeclaration = XDoc.CreateXmlDeclaration("1.0", "utf-8", "yes")
        XDoc.AppendChild(Decl)
        Dim RootNode As XmlNode = XDoc.CreateElement(DBName)
        XDoc.AppendChild(RootNode)
        Dim TablesNode As XmlNode = RootNode.AppendChild(XDoc.CreateElement("Tables"))
        For Each CurRow As DataRow In TablesTable.Rows
            Dim CurTableNode As XmlNode = TablesNode.AppendChild(XDoc.CreateElement("Table"))
            CurTableNode.InnerXml = CStr(CurRow.Item(0))
        Next
        Dim XMLFileName As String = Path.Combine(OutDir, "Data.xml")
        XDoc.Save(XMLFileName)
        Return True
    End Function

End Class
